package cn.dt70.controller;

import cn.dt70.pojo.*;
import cn.dt70.service.*;
import cn.dt70.utils.Constants;
import cn.dt70.utils.JavaMailUtil;
import cn.dt70.utils.SmsUtil;
import cn.itcast.vcode.utils.VerifyCode;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user/")
public class UserController {

    @Resource
    AqbUserService aqbUserService;

    @Resource
    AqbBankcardService aqbBankcardService;

    @Resource
    AqbGrowthService aqbGrowthService;

    @Resource
    private AqbMsgconfigService aqbMsgconfigService;

    @Resource
    private AqbAddressService addressService;

   @Resource
   private AqbInterestandcodeService aqbInterestandcodeService;

   @Resource
   private AqbInvestmentService aqbInvestmentService;

   @Resource
   private AqbCreditorService creditorService;

    @Resource
    private AqbRewardService aqbRewardService;

   @Resource
   private AqbReceptService receptService;

   @Resource
   private AqbProjectService projectService;

   @Resource
   private AqbPacketService aqbPacketService;



    //跳转用户页面
    @RequestMapping("center")
    public String userCenter(HttpSession session,Model model) {
        AqbUser user = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        if (null != user){
            String userCode = user.getUserCode();
            AqbGrowth aqbGrowth=aqbGrowthService.getGrowthByUserCode(userCode);
            AqbUser userInfoById = aqbUserService.getUserInfoById(userCode);

            model.addAttribute("aqbUser",aqbGrowth);
            model.addAttribute("aquser",userInfoById);
            return "usercenter";
        }
       return "login";
    }

    //点击签到，实现成长值增加
    @RequestMapping("qiandao")
    public String qiandao(HttpSession session,Model model){
        AqbUser user = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        String userCode = user.getUserCode();
        AqbGrowth aqbGrowth = null;
        int integral = 0;
        int status = 1;

        aqbGrowth = aqbGrowthService.getGrowthByUserCode(userCode);
        integral  = aqbGrowth.getIntegral() + 1;
        if (aqbGrowthService.updGrowthByUserCode(userCode,integral)){
            System.out.println("增加成长值成功");
            if (aqbUserService.updUserStatusByusercode(userCode,status,1)){
                System.out.println("修改用户签到信息成功");
            }
        }
        AqbUser userInfoById = aqbUserService.getUserInfoById(userCode);

        model.addAttribute("aqbUser",aqbGrowth);
        model.addAttribute("aquser",userInfoById);
        System.out.println(userInfoById.getStatus());
        return "usercenter";
    }

    //注册页面
    @RequestMapping("register")
    public String register() {

        return "register";
    }

    @RequestMapping("doRegist")
    public String doRegist(AqbUser aqbUser,String userCode,String password,Model model) {
        aqbUser=aqbUserService.addUser(aqbUser);
        if (aqbUser==null) {
            return "register";
        } else {
            aqbUser=aqbUserService.doLogin(userCode,password);
            aqbGrowthService.addUserCode(userCode);
            model.addAttribute("aqbUser", aqbUser);
            if(aqbInterestandcodeService.createCode(Integer.valueOf(aqbUser.getUserId()))){
                StringBuffer sb = new StringBuffer();

                AqbInterestandcode aic = aqbInterestandcodeService.getJxByUserId(Integer.valueOf(aqbUser.getUserId()));
                sb.append("您的加息码为：");
                sb.append(aic.getRateCode());
                JavaMailUtil.sendMail("17786203665@163.com","",Integer.valueOf(aqbUser.getUserId()),"",sb.toString());
            }else{
                System.out.println("加息码失败");
            }
            return "login";
        }
    }

    //正常访问login页面
    @RequestMapping("login")
    public String login() {
        return "login";
    }

    //表单提交过来的路径
    @RequestMapping("checkLogin")
    public String checkLogin(@RequestParam("userCode") String userCode,
                             @RequestParam("password") String password,
                             AqbUser aqbUser, Model model, HttpSession session) throws Exception {
        aqbUser = aqbUserService.doLogin(userCode, password);
        //跳转到成功页面
        if (aqbUser != null && userCode.equals(aqbUser.getUserCode()) && password.equals(aqbUser.getPassword())) {
            session.setAttribute(Constants.USER_SESSION, aqbUser);
            //类型等于1跳转后台管理页面，等于0跳转到个人页面
             if(aqbUser.getType()==1){
                 return "backend/main";
             }else if(aqbUser.getType()==0){
                 int uid=aqbUser.getUserId();
                 AqbMsgconfig aqbMsgconfig= aqbMsgconfigService.getConfigByUid(uid);
                 if(aqbMsgconfig==null){
                     aqbMsgconfig=new AqbMsgconfig();
                     aqbMsgconfig.setUid(uid);
                     aqbMsgconfig.setRecharge("110");
                     aqbMsgconfig.setInvestment("110");
                     aqbMsgconfig.setReceipt("111");
                     aqbMsgconfig.setReward("110");
                     aqbMsgconfig.setTakeOutMoney("110");
                     aqbMsgconfig.setTransferClaim("110");
                     aqbMsgconfig.setGetClaim("110");
                     aqbMsgconfig.setAnnouncement("111");
                     aqbMsgconfig.setActivity("111");
                     aqbMsgconfig.setOther("111");
                     session.setAttribute("msgCfg",aqbMsgconfig);
                 }else{
                     session.setAttribute("msgCfg",aqbMsgconfig);
                 }
                 AqbGrowth aqbGrowth=aqbGrowthService.getGrowthByUserCode(userCode);

                 //edit by Lzy
                 Double sumPrincipal = 0.0;
                 List<AqbInvestment> aqbInvestmentList = aqbInvestmentService.findBystaus(aqbUser.getUserId(),null);
                 for (AqbInvestment investment:
                         aqbInvestmentList) {

                     sumPrincipal += investment.getRestAmount();
                 }

                 List<AqbCreditor> creditorList = creditorService.findCreditorById(aqbUser.getUserId(),10000);
                 for (AqbCreditor creditor:
                         creditorList) {

                     sumPrincipal += creditor.getRestMoney()*creditor.getTransferRate();
                 }

                 model.addAttribute("sumPrincipal",sumPrincipal);

                 Double futuresumEarning = 0.0;
                 Double rate = 0.0;
                 for (AqbInvestment investment1:
                         aqbInvestmentList) {
                     rate = investment1.getRate().doubleValue();
                     futuresumEarning += investment1.getRestAmount()*rate;
                 }

                 for (AqbCreditor creditor:
                         creditorList) {

                     futuresumEarning += creditor.getRestMoney()*(1-creditor.getTransferRate());
                 }
                 model.addAttribute("futuresumEarning",futuresumEarning);

                 Double SumEarning = 0.0;
                 Double rate1 = 0.0;
                 List<AqbInvestment> aqbInvestmentList1 = aqbInvestmentService.findBystaus(aqbUser.getUserId(),4) ;
                 for (AqbInvestment investment2:
                         aqbInvestmentList1) {

                     rate1 = investment2.getRate().doubleValue();
                     SumEarning += investment2.getRestAmount()*rate1;
                 }


                 for (AqbCreditor creditor:
                         creditorList) {

                     SumEarning  += creditor.getCurrentMoney()*(1-creditor.getTransferRate());
                 }


                 model.addAttribute("SumEarning",SumEarning);

                 List<AqbInvestment> aqbInvestmentList2 = aqbInvestmentService.findById(aqbUser.getUserId());

                 model.addAttribute("aqbInvestmentList2",aqbInvestmentList2);

                 //可用奖励金
                 int couldUseReward = aqbRewardService.sumReward(aqbUser.getUserId(), 1);
                 model.addAttribute("couldUseReward",couldUseReward);

                 model.addAttribute("aqbUser",aqbGrowth);
                 model.addAttribute("aquser",aqbUser);
                 return "usercenter";
             }
       } else {
            model.addAttribute("retCode", "F");
            model.addAttribute("retMsg", "用户名或密码失败");
        }
        return "login";
    }

    /**
     * userCode防重校验
     * ajax请求
     * 返回json字符串
     */
    @RequestMapping("userCodeExists")
    @ResponseBody
    public String userCodeExists(@RequestParam("userCode") String userCode) {
        AqbUser aqbUser = aqbUserService.getByUserCode(userCode);
        if (aqbUser.getUserCode() == null) {
            return "{\"retCode\":\"T\"}";
        }
        return "{\"retCode\":\"F\"}";
    }


    /*退出*/
    @RequestMapping("loginout")
    public String loginout(HttpSession session) {
        session.removeAttribute(Constants.USER_SESSION);
        return "redirect:login";
    }

    @RequestMapping("card")
    public String card() {
        return "home-register-openbankid";
    }

    /*开通账户页面*/
    @RequestMapping("openCard")
    public String open(AqbBankcard aqbBankcard,HttpSession session) {
        AqbBankcard aqbBankcard1=(AqbBankcard) session.getAttribute(Constants.USER_SESSION);
        if (aqbBankcardService.addCard(aqbBankcard1)) {
            return "usercenter";
        }
        return "home-register-openbankid";
    }

    /*跳转忘记密码页面*/
    @RequestMapping("forget")
    public String forget() {
        return "forget";
    }

    /*添加地址*/
   @RequestMapping("address")
    public String address(Model model,
                          @Param("addressName")String addressName,
                          @Param("provicace")String provicace,
                          @Param("city")String city,
                          @Param("district")String district,
                          @Param("address")String address,
                          @Param("phone")String phone, HttpSession session){
       AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
       boolean flag=addressService.addAddress(aqbUser.getUserId(),addressName,provicace,city,
                                          district,address,phone);
       if(flag==true){
           return "usercenter";
       }else{
           return "usercenter-accountcontrol-userverify";
       }
    }

    /*添加邮箱*/
    @RequestMapping("email")
    public String saveEmail(String email,HttpSession session){
        if(aqbUserService.addemail(email)){
            return "usercenter";
        }else{
            return "usercenter-accountcontrol-userverify";
        }
    }
    /*更改*/
    @RequestMapping(value = "modify",method =RequestMethod.GET)
    public String change(@Param("userId") String userId, Model model) {
        model.addAttribute("aqbUser",aqbUserService.getByUserId(userId));
        return "usercenter-accountcontrol-userverify";
    }

    //修改用户名
    @RequestMapping(value = "change",method = RequestMethod.POST)
    public String modify(AqbUser aqbUser,HttpSession session){
         AqbUser aqbUser1=(AqbUser) session.getAttribute(Constants.USER_SESSION);
         aqbUser1.setUserCode(aqbUser.getUserCode());
        //调用service的修改方法
        if(aqbUserService.modifyAqbUser(aqbUser1)){
            return "usercenter";
        }else{
            return "usercenter-accountcontrol-userverify";
        }
    }

    //修改密码
    @RequestMapping(value = "pwd",method = RequestMethod.POST)
    public String modifypwd(AqbUser aqbUser,HttpSession session){
        AqbUser aqbUser1=(AqbUser) session.getAttribute(Constants.USER_SESSION);
        aqbUser1.setPassword(aqbUser.getPassword());
        //调用service的修改方法
        if(aqbUserService.modifyAqbUser(aqbUser1)){
            return "login";
        }else{
            return "usercenter-accountcontrol-userverify";
        }
    }

    //修改手机
    @RequestMapping(value = "phone",method = RequestMethod.POST)
    public String modifyphone(AqbUser aqbUser,HttpSession session){
        AqbUser aqbUser1=(AqbUser) session.getAttribute(Constants.USER_SESSION);
        aqbUser1.setPhone(aqbUser.getPhone());
        //调用service的修改方法
        if(aqbUserService.modifyAqbUser(aqbUser1)){
            return "usercenter";
        }else{
            return "usercenter-accountcontrol-userverify";
        }
    }

    /*找回密码*/
    @RequestMapping("find")
    public String find(AqbUser aqbUser,Model model){
        model.addAttribute("userCode",aqbUser.getUserCode());
        //model.addAttribute("email",aqbUser.getEmail());
       /* boolean aqbUser1=aqbUserService.findEmailByUserCode(aqbUser.getUserCode(),aqbUser.getEmail());
        if(aqbUser1 ==false){
            model.addAttribute("retCode", "F");
            model.addAttribute("retMsg", "邮箱未注册，不能使用！");
            return "forget";
        }*/
        return "usercenter-find";
    }

    /*手机找回*/
    @RequestMapping("findPwd")
    public String findPwd(AqbUser aqbUser,Model model){

          if(aqbUserService.modifyPwd(aqbUser.getPassword(),aqbUser.getUserCode())){
              return "login";
          }
        return "usercenter-find";
    }

    /*找回密码*/
    @RequestMapping("findemail")
    public String findemail(AqbUser aqbUser,Model model){
        model.addAttribute("userCode",aqbUser.getUserCode());
        aqbUser=aqbUserService.findEmailByUserCode(aqbUser.getUserCode());
        if(aqbUser == null){
            model.addAttribute("retCode", "F");
            model.addAttribute("retMsg", "邮箱未注册，不能使用！");
            return "forget";
        }else{
            return "usercenter-find";
        }
    }
    /*邮箱找回*//*
    @RequestMapping("findPwd")
    public String findpwd(AqbUser aqbUser,Model model){
        model.addAttribute("email",aqbUser.getEmail());
        if(aqbUserService.modifyPwd(aqbUser.getPassword(),aqbUser.getUserCode())){
            return "login";
        }
        return "usercenter-find";
    }*/
    /*验证码*/
    @RequestMapping("verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("验证huoqu");
        VerifyCode vc = new VerifyCode();//1. 创建验证码类
        BufferedImage image = vc.getImage(); // 2. 得到验证码图片
        request.getSession().setAttribute("num", vc.getText());//3. 把图片上的文本保存到session中
        VerifyCode.output(image, response.getOutputStream());//4. 把图片响应给客户端
    }

    @RequestMapping("isVerifyCode")
    public void check(HttpServletRequest request, HttpServletResponse response, String verifycode) throws ServletException, IOException {
        System.out.println("验证方法");
        Writer out = response.getWriter();
        if (verifycode.equals(request.getSession().getAttribute("num"))) {
            request.getSession().setAttribute("result", true);
            System.out.println("T");
            out.write("T");
        } else {
            request.getSession().setAttribute("result", false);
            System.out.println("F");
            out.write("F");
        }
    }

    @RequestMapping("sms")
    public  void sendSms(HttpSession session,String phoneNum){
        System.out.println("发送手机验证码");
        String code="";
        Random rd = new Random();
        for (int i = 0; i < 4; i++) {
            int num=rd.nextInt(9);
            code+=num;
        }
        System.out.println("手机验证码："+code);
        session.setAttribute("phoneCode",code);
        SmsUtil.sendSms(phoneNum,code);
    }

    @RequestMapping("checkPhone")
    public  void checkPhone(HttpSession session,String phoneCode, HttpServletResponse response) throws Exception{
        PrintWriter out=response.getWriter();
       if(phoneCode.equals(session.getAttribute("phoneCode"))){
          out.write("T");
       }else {
           out.write("F");
       }
    }

    @RequestMapping("sendMail")
    public void sendMail(String mail,String type,@RequestParam(value = "userName",required=false) String userName,HttpSession session){
        String mailCode="";
        System.out.println("进入发送邮件");
        Random rd = new Random();
        for (int i = 0; i < 4; i++) {
            int num=rd.nextInt(9);
            mailCode+=num;
        }
        session.setAttribute("MailCode",mailCode);
      //  AqbUser aqbUser=(AqbUser) session.getAttribute(Constants.USER_SESSION);
        StringBuffer sf=new StringBuffer();
        if(type.equals("forget")){
            sf.append("<a href=\"http://localhost:8080/user/checkMail?MailCode=");
            sf.append(mailCode);
            sf.append("&type=forget");
        }else {
            sf.append("<a href=\"http://localhost:8080/user/checkMail?MailCode=");
            sf.append(mailCode);
            sf.append("&type=mailBind");
        }
        sf.append("&userName=");
        sf.append(userName);
        sf.append("\">");
        sf.append(" <FONT   face=\"MS   UI   Gothic\"   size=\"3\"><b>点击这里</b></FONT>");
        sf.append("</a>");
        JavaMailUtil.sendMail(mail,"",1,"邮箱验证",sf.toString());
    }

    @RequestMapping("checkMail")
    public String checkMail(String MailCode,String userName,String type,HttpSession session,Model model) throws Exception{
        model.addAttribute("userName",userName);
        if(MailCode.equals(session.getAttribute("MailCode"))&&type.equals("mailBind")){
            return "usercenter-accountcontrol-userverify";
        }else {
            return "usercenter-find";
        }


    }


}